package com.example.springboot2.service;

import com.example.springboot2.entity.GoodsCategory;
import com.example.springboot2.entity.Merchant;
import com.example.springboot2.exception.BusinessException;
import com.example.springboot2.repository.GoodsCategoryRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品分类服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GoodsCategoryService {

    private final GoodsCategoryRepository goodsCategoryRepository;
    private final MerchantService merchantService;

    /**
     * 根据ID查找分类
     */
    public GoodsCategory findById(Long id) {
        return goodsCategoryRepository.findById(id)
                .orElseThrow(() -> new BusinessException("商品分类不存在"));
    }

    /**
     * 获取商家所有分类
     */
    public List<GoodsCategory> getGoodsCategories(Long userId) {
        Merchant merchant = merchantService.getMerchantInfo(userId);
        return goodsCategoryRepository.findByMerchantAndIsEnabledTrueOrderBySortOrder(merchant);
    }

    /**
     * 获取顶级分类
     */
    public List<GoodsCategory> getTopCategories(Long userId) {
        Merchant merchant = merchantService.getMerchantInfo(userId);
        return goodsCategoryRepository.findByMerchantAndParentIsNullAndIsEnabledTrueOrderBySortOrder(merchant);
    }

    /**
     * 获取子分类
     */
    public List<GoodsCategory> getSubCategories(Long userId, Long parentId) {
        Merchant merchant = merchantService.getMerchantInfo(userId);
        GoodsCategory parent = null;
        if (parentId != null) {
            parent = findById(parentId);
            // 验证父分类是否属于当前商家
            if (!parent.getMerchant().getId().equals(merchant.getId())) {
                throw new BusinessException("无权访问该分类");
            }
        }
        return goodsCategoryRepository.findByMerchantAndParentAndIsEnabledTrueOrderBySortOrder(merchant, parent);
    }

    /**
     * 创建商品分类
     */
    @Transactional
    public GoodsCategory createGoodsCategory(Long userId, GoodsCategory category) {
        Merchant merchant = merchantService.getMerchantInfo(userId);
        category.setMerchant(merchant);
        
        // 如果有父分类，验证父分类是否属于当前商家
        if (category.getParent() != null) {
            GoodsCategory parent = findById(category.getParent().getId());
            if (!parent.getMerchant().getId().equals(merchant.getId())) {
                throw new BusinessException("无权使用该父分类");
            }
            category.setParent(parent);
        }
        
        // 设置默认值
        if (category.getSortOrder() == null) {
            category.setSortOrder(0);
        }
        if (category.getIsEnabled() == null) {
            category.setIsEnabled(true);
        }
        category.setGoodsCount(0);
        
        GoodsCategory savedCategory = goodsCategoryRepository.save(category);
        log.info("商家创建商品分类: {} - {}", merchant.getShopName(), category.getName());
        return savedCategory;
    }

    /**
     * 更新商品分类
     */
    @Transactional
    public GoodsCategory updateGoodsCategory(Long userId, Long categoryId, GoodsCategory categoryInfo) {
        Merchant merchant = merchantService.getMerchantInfo(userId);
        GoodsCategory existingCategory = findById(categoryId);
        
        // 验证分类是否属于当前商家
        if (!existingCategory.getMerchant().getId().equals(merchant.getId())) {
            throw new BusinessException("无权修改该分类");
        }
        
        // 更新分类信息
        existingCategory.setName(categoryInfo.getName());
        existingCategory.setDescription(categoryInfo.getDescription());
        existingCategory.setIcon(categoryInfo.getIcon());
        existingCategory.setSortOrder(categoryInfo.getSortOrder());
        existingCategory.setIsEnabled(categoryInfo.getIsEnabled());
        
        // 如果有父分类，验证父分类是否属于当前商家
        if (categoryInfo.getParent() != null) {
            GoodsCategory parent = findById(categoryInfo.getParent().getId());
            if (!parent.getMerchant().getId().equals(merchant.getId())) {
                throw new BusinessException("无权使用该父分类");
            }
            // 检查是否会形成循环引用
            if (isCircularReference(existingCategory, parent)) {
                throw new BusinessException("不能将分类设置为自己的子分类");
            }
            existingCategory.setParent(parent);
        } else {
            existingCategory.setParent(null);
        }
        
        GoodsCategory savedCategory = goodsCategoryRepository.save(existingCategory);
        log.info("商家更新商品分类: {} - {}", merchant.getShopName(), categoryInfo.getName());
        return savedCategory;
    }

    /**
     * 删除商品分类
     */
    @Transactional
    public void deleteGoodsCategory(Long userId, Long categoryId) {
        Merchant merchant = merchantService.getMerchantInfo(userId);
        GoodsCategory category = findById(categoryId);
        
        // 验证分类是否属于当前商家
        if (!category.getMerchant().getId().equals(merchant.getId())) {
            throw new BusinessException("无权删除该分类");
        }
        
        // 检查是否有子分类
        List<GoodsCategory> subCategories = goodsCategoryRepository
                .findByMerchantAndParentAndIsEnabledTrueOrderBySortOrder(merchant, category);
        if (!subCategories.isEmpty()) {
            throw new BusinessException("该分类下还有子分类，不能删除");
        }
        
        // 检查是否有商品使用该分类
        if (category.getGoodsCount() > 0) {
            throw new BusinessException("该分类下还有商品，不能删除");
        }
        
        goodsCategoryRepository.delete(category);
        log.info("商家删除商品分类: {} - {}", merchant.getShopName(), category.getName());
    }

    /**
     * 检查是否会形成循环引用
     */
    private boolean isCircularReference(GoodsCategory category, GoodsCategory newParent) {
        if (newParent == null) {
            return false;
        }
        
        // 如果新父分类就是当前分类，直接返回true
        if (newParent.getId().equals(category.getId())) {
            return true;
        }
        
        // 递归检查新父分类的父分类链
        GoodsCategory current = newParent.getParent();
        while (current != null) {
            if (current.getId().equals(category.getId())) {
                return true;
            }
            current = current.getParent();
        }
        
        return false;
    }

    /**
     * 获取分类详情
     */
    public GoodsCategory getCategoryDetail(Long userId, Long categoryId) {
        Merchant merchant = merchantService.getMerchantInfo(userId);
        GoodsCategory category = findById(categoryId);
        
        // 验证分类是否属于当前商家
        if (!category.getMerchant().getId().equals(merchant.getId())) {
            throw new BusinessException("无权访问该分类");
        }
        
        return category;
    }

    /**
     * 更新分类商品数量
     */
    @Transactional
    public void updateCategoryGoodsCount(Long categoryId, int count) {
        GoodsCategory category = findById(categoryId);
        category.setGoodsCount(Math.max(0, category.getGoodsCount() + count));
        goodsCategoryRepository.save(category);
    }
}
